package com.ruoyi.feike.service.impl;

import java.io.*;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.DealerInformation;
import com.ruoyi.feike.domain.DealerSectorContractgroup;
import com.ruoyi.feike.domain.vo.BasicContractVO;
import com.ruoyi.feike.mapper.DealerInformationMapper;
import com.ruoyi.feike.mapper.DealerSectorContractgroupMapper;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.BookmarksNavigator;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.feike.mapper.BasicContractMapper;
import com.ruoyi.feike.domain.BasicContract;
import com.ruoyi.feike.service.IBasicContractService;
import org.springframework.util.CollectionUtils;

/**
 * 合同信息Service业务层处理
 *
 * @author ybw
 * @date 2022-07-19
 */
@Service
public class BasicContractServiceImpl implements IBasicContractService
{
    @Autowired
    private BasicContractMapper basicContractMapper;

    @Autowired
    private DealerInformationMapper dealerInformationMapper;

    @Autowired
    private DealerSectorContractgroupMapper dealerSectorContractgroupMapper;


    /**
     * 查询合同信息
     *
     * @param id 合同信息ID
     * @return 合同信息
     */
    @Override
    public BasicContract selectBasicContractById(String id)
    {
        return basicContractMapper.selectBasicContractById(id);
    }

    /**
     * 查询合同信息列表
     *
     * @param basicContract 合同信息
     * @return 合同信息
     */
    @Override
    public List<BasicContract> selectBasicContractList(BasicContract basicContract)
    {
        return basicContractMapper.selectBasicContractList(basicContract);
    }

    /**
     * 查询合同信息列表并根据合同名称主机厂分组
     *
     * @param basicContract 合同信息
     * @return 合同信息
     */
    @Override
    public List<BasicContract> selectBasicContractListgroupby(BasicContract basicContract)
    {
        return basicContractMapper.selectBasicContractListgroupby(basicContract);
    }

    /**
     * 新增合同信息
     *
     * @param basicContract 合同信息
     * @return 结果
     */
    @Override
    public int insertBasicContract(BasicContract basicContract)
    {
        String location = "/profile/template/"+basicContract.getSector()+"/"+basicContract.getContractname()+".docx";
        basicContract.setId(IdUtils.simpleUUID());
        if(basicContract.getSector().equals("Naveco")){
            basicContract.setSector("Naveco Daily");
        }
        basicContract.setContractlocation(location);
        return basicContractMapper.insertBasicContract(basicContract);
    }

    /**
     * 修改合同信息
     *
     * @param basicContract 合同信息
     * @return 结果
     */
    @Override
    public int updateBasicContract(BasicContract basicContract)
    {
        return basicContractMapper.updateBasicContract(basicContract);
    }

    /**
     * 批量删除合同信息
     *
     * @param ids 需要删除的合同信息ID
     * @return 结果
     */
    @Override
    public int deleteBasicContractByIds(String[] ids)
    {
        return basicContractMapper.deleteBasicContractByIds(ids);
    }

    /**
     * 删除合同信息信息
     *
     * @param id 合同信息ID
     * @return 结果
     */
    @Override
    public int deleteBasicContractById(String id)
    {
        return basicContractMapper.deleteBasicContractById(id);
    }

    /**
     * 根据优先级、主机厂、授信类型查询对应合同查询合同信息列表
     *
     * @param resultMap
     * @return 合同信息
     */
    @Override
    public List<BasicContract> listBasicContract(Map<String, Object> resultMap)
    {
        return basicContractMapper.listBasicContract(resultMap);
    }

    @Override
    public BasicContract selectBasicContractBySector(String sector,String dealerName) {
        List<BasicContract> basicContracts = null;
        try {
            basicContracts = basicContractMapper.selectBasicContractBySector(sector);
            if(CollectionUtils.isEmpty(basicContracts)){
                return null;
            }
            String contractlocation = basicContracts.get(0).getContractlocation();
            if(StringUtils.isEmpty(contractlocation)){return null;}
            //加载包含书签的Word文档
            Document doc = new Document();
            doc.loadFromFile(RuoYiConfig.getProfile() + contractlocation);
            //定位到指定书签位置
            BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);

            //用文本内容替换原有书签位置的文本，新替换的内容与原文格式一致
            bookmarksNavigator.moveToBookmark("DealerName");
            bookmarksNavigator.replaceBookmarkContent(dealerName,true);
            bookmarksNavigator.moveToBookmark("DealerName1");
            bookmarksNavigator.replaceBookmarkContent(dealerName,true);
            //签署合同日期
            bookmarksNavigator.moveToBookmark("签署合同日期");
            bookmarksNavigator.replaceBookmarkContent(DateUtils.datePathCn(),true);
            //DEMO抵押合同车辆品牌
            bookmarksNavigator.moveToBookmark("DEMO抵押合同车辆品牌");
            bookmarksNavigator.replaceBookmarkContent(sector,true);
            //经销商法人
            //获取法人中文名
            DealerInformation dealerInformation = dealerInformationMapper.selectInfoBySectorAndDealerName(sector, dealerName);
            if(ObjectUtil.isNotNull(dealerInformation)){
                bookmarksNavigator.moveToBookmark("经销商法人");
                bookmarksNavigator.replaceBookmarkContent(StringUtils.isEmpty(dealerInformation.getLegalRepresentativeCN())?"":dealerInformation.getLegalRepresentativeCN(),true);
            }
            DealerSectorContractgroup sectorContractGroup = new DealerSectorContractgroup();
            sectorContractGroup.setDealername(dealerName);
            sectorContractGroup.setSector(sector);
            sectorContractGroup.setContractname("人民币循环贷款合同");

            DealerSectorContractgroup shiJiaChe = new DealerSectorContractgroup();
            shiJiaChe.setDealername(dealerName);
            shiJiaChe.setSector(sector);
            shiJiaChe.setContractname("试乘试驾车抵押合同（E已更改）");

            List<DealerSectorContractgroup> contractRMB = dealerSectorContractgroupMapper.getContractGroup(sectorContractGroup);
            //合同号
            String contractNumber = "";
            //合同号M
            String contractNumberM = "";
            if(CollectionUtil.isNotEmpty(contractRMB)){
                //最大数
                String maxS = dealerSectorContractgroupMapper.selectMaxSerialNumber(shiJiaChe);


                DealerSectorContractgroup contractRm1= contractRMB.get(0);

                if(StringUtils.isEmpty(maxS) || maxS.equals("")){
                    contractNumberM = dealerInformation.getDealerCode()+"DEMO"+contractRm1.getContractnumber().split("F")[1]+"-M-2";
                }else {
                    String max = String.valueOf(Double.valueOf(maxS).intValue());
                    contractNumberM = dealerInformation.getDealerCode()+"DEMO"+contractRm1.getContractnumber().split("F")[1]+"-M-"+max;
                }

                contractNumber = dealerInformation.getDealerCode()+"DEMO"+contractRm1.getContractnumber().split("F")[1];
            }else {
                //合同编号
//                int number = Integer.parseInt(dealerSectorContractgroupMapper.selectMaxNumber(sectorContractGroup))+1;
//                //定义编号格式001
//                DecimalFormat decimalFormat = new DecimalFormat("000");
//                String format = decimalFormat.format(number);

                String format = "001";

                contractNumberM = dealerInformation.getDealerCode()+"DEMO"+DateUtils.dateTimeNow("yy")+DateUtils.getMonthEN()+format+"-M";

                contractNumber = dealerInformation.getDealerCode()+"DEMO"+DateUtils.dateTimeNow("yy")+DateUtils.getMonthEN()+format;

                //历史合同表记录 试乘试驾车抵押合同（E已更改）
                sectorContractGroup.setContractnumber(dealerInformation.getDealerCode()+"F"+DateUtils.dateTimeNow("yy")+DateUtils.getMonthEN()+format);
                sectorContractGroup.setExpDate(DateUtils.getDate());
                sectorContractGroup.setDealerCode(dealerInformation.getDealerCode());
                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(sectorContractGroup);


            }

            List<DealerSectorContractgroup> contractGroup = dealerSectorContractgroupMapper.getContractGroup(shiJiaChe);
            if(CollectionUtil.isNotEmpty(contractGroup)){
                //历史合同表记录 试乘试驾车抵押合同（E已更改）
                shiJiaChe.setContractname("试乘试驾车抵押合同（E已更改）");
                shiJiaChe.setContractnumber(contractNumberM);
                shiJiaChe.setExpDate(DateUtils.getDate());
                shiJiaChe.setDealerCode(dealerInformation.getDealerCode());
                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(shiJiaChe);
            }else {
                //历史合同表记录 试乘试驾车抵押合同（E已更改）
                shiJiaChe.setContractname("试乘试驾车抵押合同（E已更改）");
                shiJiaChe.setContractnumber(dealerInformation.getDealerCode()+"DEMO"+DateUtils.dateTimeNow("yy")+DateUtils.getMonthEN()+"001"+"-M-1");
                shiJiaChe.setExpDate(DateUtils.getDate());
                shiJiaChe.setDealerCode(dealerInformation.getDealerCode());
                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(shiJiaChe);
            }



            //DEMO抵押合同合同号 书签写入
            bookmarksNavigator.moveToBookmark("DEMO抵押合同合同号");
            bookmarksNavigator.replaceBookmarkContent(contractNumberM,true);

            //DEMO抵押合同合同号1
            bookmarksNavigator.moveToBookmark("DEMO抵押合同合同号1");
            bookmarksNavigator.replaceBookmarkContent(contractNumber,true);

            //ContractNumberD
            bookmarksNavigator.moveToBookmark("ContractNumberD");
            bookmarksNavigator.replaceBookmarkContent(contractNumber,true);


            String filePath = "/"+RuoYiConfig.getProfile()+"/profile/template/"+sector+"/"+dealerName+"试驾车抵押合同"+".docx";
//            File file = new File(filePath);
//            if(FileUtil.isEmpty(file)){
//                FileUtil.cleanEmpty(file);
//            }

            //保存文档FileFormat.Docx_2013
            doc.saveToFile(filePath, FileFormat.Docx_2013);
            doc.dispose();

            //重新读取生成的文档
            InputStream is = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os=new FileOutputStream(filePath);
            document.write(os);
            os.flush();
            os.close();
            document.close();
            BasicContract basicContract = basicContracts.get(0);
            basicContract.setContractlocation("/profile/template/"+sector+"/"+dealerName+"试驾车抵押合同"+".docx");
            basicContract.setContractNumber(contractNumber);
            return basicContract;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改分类后的合同信息
     *
     * @param basicContractVO
     * @return 结果
     */
    @Override
    public int updateBasicContractgroupby(BasicContractVO basicContractVO)
    {
        return basicContractMapper.updateBasicContractgroupby(basicContractVO);
    }
}
